package com.example.mall.user.svc.app.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.mall.common.constants.CodeEnum;
import com.example.mall.common.exception.BizException;
import com.example.mall.user.api.dto.UserDTO;
import com.example.mall.user.api.service.IUserService;
import com.example.mall.user.svc.app.cmd.CreateUserCmd;
import com.example.mall.user.svc.domain.model.entity.User;
import com.example.mall.user.svc.infr.mapper.UserMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author Mickey
 * @since 2022/4/18
 **/
@Service
@AllArgsConstructor
public class UserQryService implements IUserService {

    private final UserMapper userMapper;
    private final UserAppService userAppService;

    public Optional<User> loadOrCreate(String uniqueId, Integer loginMode) {
        return Optional.of(userMapper.byUniqueId(uniqueId)
                .orElseGet(() -> userMapper.selectById(userAppService.create(new CreateUserCmd(uniqueId, "xx")))));
    }

    public Optional<User> byUniqueId(String uniqueId) {
        return userMapper.byUniqueId(uniqueId);
    }

    public Optional<User> byId(Long id) {
        return Optional.of(userMapper.selectById(id));
    }

    public List<User> list() {
        return userMapper.selectList(new LambdaQueryWrapper<>());
    }

    @Override
    public UserDTO loadByUniqueId(String uniqueId) {
        return byUniqueId(uniqueId).map(User::converterToUserDTO).orElseThrow(() -> new BizException(CodeEnum.FAIL));
    }
}
